<template>
	<div>
		<el-card shadow="never" header="个人信息" v-loading="loading">
			<el-form ref="formRef" :model="form" label-width="120px" style="margin-top:20px;">
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="form.email" disabled></el-input>
				</el-form-item>
				<el-form-item label="头像" prop="avatar">
					<el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload">
						<img v-if="form.avatar" :src="formAvatar(form.avatar)" class="avatar" alt="">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="昵称" prop="nickname">
					<el-input v-model="form.nickname"></el-input>
				</el-form-item>
				<el-form-item label="手机号码" prop="mobile">
					<el-input v-model="form.mobile"></el-input>
				</el-form-item>
				<el-form-item label="个性签名" prop="description">
					<el-input v-model="form.description" type="textarea"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit">保存</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {getUserDetailApi, updateUserApi} from "@/api/modules/auth.ts";
import {formAvatar} from "@/utils/user.ts";
import {fileUpload} from "@/utils/upload.ts";
import {ElMessage} from "element-plus";

const form = reactive({
	email: "",
	nickname: "",
	avatar: "" as string | Blob,
	mobile: "",
	description: ""
})

const loading = ref(true);
const loadDetail = async () => {
	loading.value = true;
	try {
		const detailData = await getUserDetailApi();
		form.email = detailData.data.data.email;
		form.nickname = detailData.data.data.nickname;
		form.avatar = detailData.data.data.avatar ?? "";
		form.mobile = detailData.data.data.mobile ?? "";
		form.description = detailData.data.data.description ?? "";
	} finally {
		loading.value = false;
	}
}

const beforeAvatarUpload = (file: File) => {
	const result = fileUpload(file);
	result.then(blob => {
		form.avatar = blob;
	}).catch(error => {
		ElMessage.error(error);
	});
	return false;
};
const submitting = ref(false);
const onSubmit = async () => {
	if (submitting.value) return;
	try {
		submitting.value = true;
		const updateData = await updateUserApi(form);
		ElMessage.success(updateData.message);
	} catch (error) {
		console.log(error);
	} finally {
		submitting.value = false;
	}
};

onMounted(() => {
	loadDetail();
});
</script>
<style scoped>

.avatar-uploader ::v-deep(.el-upload) {
	width: 120px;
	height: 120px;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 1px dashed #d9d9d9;
	border-radius: 50%;
	cursor: pointer;
	overflow: hidden;
}

.avatar-uploader ::v-deep(.el-upload) .avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
}

.avatar-uploader ::v-deep(.el-upload) .avatar {
	width: 100%;
	height: 100%;
	object-fit: cover;
}
</style>